package com.siyoumi.sh.modules.jm;

import com.siyoumi.sh.component.ThreadContext;
import com.siyoumi.sh.modules.common.IHandle;
import com.siyoumi.sh.modules.jm.entity.*;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XJson;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

//积分商城
@Slf4j
public class FunMallHandle
        extends JmHandleBase
        implements IHandle {
    //fun_mall wan 用户序号 商品ID序号

    @Override
    @SneakyThrows
    public void run() {
        List<String> args = ThreadContext.getArgs();
        if (args.size() < 3) {
            log.error("args参数异常，参考：fun_mall wan 商品ID序号 用户序号，{}", args);
            return;
        }
        String server = args.get(1);

        JmApiData apiData = getApiDataByServer(server);
        if (apiData == null) {
            log.error("args server参数异常，{}", args);
            return;
        }
        setJmApiData(apiData);

        Integer userIndex = XStr.toInt(args.get(2));

        List<JmApiToken> apiTokenArr = getJmApiData().getJmApiTokens();
        if (apiTokenArr.size() <= 0) {
            log.error("未配置TOKEN");
            return;
        }
        if (apiTokenArr.size() - 1 < userIndex) {
            log.error("args 用户序号参数异常，{}", args);
            return;
        }
        JmApiToken apiToken = apiTokenArr.get(userIndex);


        List<FunMallGoods> listGoods = funMallGoodsList(apiToken);
        List<FunMallGoods> listGoodsTrue = new ArrayList<>();

        DateTimeFormatter mmdd = DateTimeFormatter.ofPattern("MM-dd HH:mm");

        Integer index = 0;
        for (FunMallGoods goods : listGoods) {
            XReturn rDate = goods.validDate();
            if (rDate.getErrCode() == 20022) {
                //已结束 不显示
                //continue;
            }
            if (goods.getStcnt_count_left() <= 0) {
                //库存为0
                //continue;
            }

            log.info("[{}]{}, 积分：{} 库存：{} 开始时间：{}", index, goods.getAbc_name()
                    , goods.getAbc_fun()
                    , goods.getStcnt_count_left()
                    , XDate.format(goods.getAbc_begin_time(), mmdd)
            );
            index++;

            listGoodsTrue.add(goods);
        }

        Integer goodsIndex;
        if (args.size() >= 4) {
            goodsIndex = XStr.toInt(args.get(3));
        } else {
            String s = "";
            while (true) {
                log.info("请输入需要抢的商品序号：");
                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                s = br.readLine();
                if (XStr.hasAnyText(s)) {
                    break;
                }
            }
            goodsIndex = XStr.toInt(s, 0);
        }

        if (goodsIndex > (listGoodsTrue.size() - 1)) {
            log.info("你请输入商品序号异常");
            return;
        }

        FunMallGoods goods = listGoodsTrue.get(goodsIndex);
        funMallGoodsInfo(apiToken, goods.getAbc_id());
        qiang(apiToken, goods);
    }

    /**
     * 开始抢购
     */
    public void qiang(JmApiToken apiToken, FunMallGoods goods) {
        log.info("{}-开始竞拍", goods.getAbc_name());
        log.info("{}-离竞拍结束还剩：{}秒", goods.getAbc_name(), goods.leftSecond());

        Integer fun = getFun(apiToken);
        log.info("{}-积分总数：{}", apiToken.getName(), fun);

        XReturn r = XReturn.getR(0);
        log.info("等待状态");
        while (true) {

            log.info("距离结束还剩：{}秒", goods.leftSecond());

            if (goods.leftSecond() <= 3) {
                log.info("最后3秒进入战斗状态");
                log.info("开始兑换");

                r = funExchange(apiToken, goods.getAbc_id());
                if (r.getErrCode() == 20037) {
                    //未开始继续抢
                    continue;
                } else {
                    break;
                }
            } else if (goods.leftSecond() <= 30) {
                log.info("最后30秒进入作战状态");
                sleepAndLog(1);
            } else {
                //更新商品最新信息
                FunMallGoods nowGoods = funMallGoodsInfo(apiToken, goods.getAbc_id());
                if (nowGoods != null) {
                    goods = nowGoods;
                }
                sleepAndLog(30);
            }
        }

        if (r.err()) {
            sendMsg(goods.getAbc_name() + ":" + XJson.toJSONString(r));
            return;
        }
    }


    //兑换
    public XReturn funExchange(JmApiToken apiToken, String goodsId) {
        String apiUrl = XStr.concat(getApiRoot(), "__api_java__/z_app/mall_fun_b/0/web/zz_api__api__goodsInfo__funcExchange?"
                , "site_id=", getSiteId()
                , "&id=", goodsId
                , "&", apiToken.getWxFromQuery()
        );

        XReturn r = forApi(apiUrl);
        return r;
    }

    //商品列表
    public List<FunMallGoods> funMallGoodsList(JmApiToken apiToken) {
        String apiUrl = XStr.concat(getApiRoot(), "__api_java__/z_app/mall_fun_b/0/web/zz_api__api__view__funcListGoods?"
                , "type=&site_id=", getSiteId()
                , "&", apiToken.getWxFromQuery()
        );

        List<FunMallGoods> listGoods = new ArrayList<>();
        XReturn r = forApi(apiUrl);
        if (r.err()) {
            return listGoods;
        }

        List<Map<String, Object>> list = r.getData("list");
        for (Map<String, Object> data : list) {
            Map<String, Object> mapGoods = (Map<String, Object>) data.get("goods");

            FunMallGoods goods = new FunMallGoods();
            goods.setAbc_begin_time(XDate.parse((String) mapGoods.get("abc_begin_time")));
            goods.setAbc_end_time(XDate.parse((String) mapGoods.get("abc_end_time")));
            goods.setAbc_fun((Integer) mapGoods.get("abc_fun"));
            goods.setAbc_name((String) mapGoods.get("abc_name"));
            goods.setAbc_id((String) mapGoods.get("abc_id"));
            goods.setStcnt_count_left((Integer) mapGoods.get("stcnt_count_left"));

            listGoods.add(goods);
        }

        return listGoods;
    }

    //商品详情
    public FunMallGoods funMallGoodsInfo(JmApiToken apiToken, String goodsId) {
        String apiUrl = XStr.concat(getApiRoot(), "__api_java__/z_app/mall_fun_b/0/web/zz_api__api__goodsInfo?"
                , "type=&site_id=", getSiteId()
                , "&id=", goodsId
                , "&", apiToken.getWxFromQuery()
        );

        XReturn r = forApi(apiUrl);
        if (r.err()) {
            return null;
        }

        Map<String, Object> mapGoods = r.getData("goods");
        Map<String, Object> mapStock = r.getData("stock");

        FunMallGoods goods = new FunMallGoods();
        goods.setAbc_begin_time(XDate.parse((String) mapGoods.get("abc_begin_time")));
        goods.setAbc_end_time(XDate.parse((String) mapGoods.get("abc_end_time")));
        goods.setAbc_fun((Integer) mapGoods.get("abc_fun"));
        goods.setAbc_name((String) mapGoods.get("abc_name"));
        goods.setAbc_id((String) mapGoods.get("abc_id"));
        goods.setStcnt_count_left((Integer) mapStock.get("stcnt_count_left"));


        return goods;
    }
}
